package com.rm.common.shiro;

import java.util.List;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.rm.system.model.Log;
import com.rm.system.model.Res;

/***
 * 让 shiro 基于 url 拦截
 * 
 * 主要 数据库中也用url 保存权限
 * 
 * @author 12
 * 
 */
public class ShiroInterceptor implements Interceptor {
	 private static ShiroExt ext = new ShiroExt();

	/**
	 * 获取全部 需要控制的权限
	 */
	private static List<String> urls;

	public static void updateUrls() {
		urls = Res.dao.getUrls();
	}

	public void intercept(Invocation ai) {
		if (urls == null)
			urls = Res.dao.getUrls();

		String url = ai.getActionKey();
		try {

			if (url.contains("delete"))
				Log.dao.insert(ai.getController(), Log.EVENT_DELETE);
			else if (url.contains("add"))
				Log.dao.insert(ai.getController(), Log.EVENT_ADD);
			else if (url.contains("edit"))
				Log.dao.insert(ai.getController(), Log.EVENT_UPDATE);
			else if (url.contains("grant"))
				Log.dao.insert(ai.getController(), Log.EVENT_GRANT);

 
			//已经在数据库中配置的才检查，否则忽略
			if (urls.contains(url) && !ext.hasPermission(url))
				ai.getController().renderError(401);
			   
			
		} catch (Exception e) {
			e.printStackTrace();
			ai.getController().renderError(401);
		}

		ai.invoke();

	}

}
